<template>
  <div class="class-circle-page">
    <div class="back-btn-wrapper">
      <el-button type="text" @click="goBack" class="back-btn">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </el-button>
    </div>
    <div class="page-header">
      <div class="header-content">
        <h1>班级圈</h1>
        <p>教师创建班级圈，学生加入交流，促进师生互动</p>
      </div>
      <div class="header-actions">
        <el-button 
          v-if="userInfo.role === 'TEACHER'" 
          type="primary" 
          @click="showCreateDialog = true"
        >
          <el-icon><Plus /></el-icon>
          创建班级圈
        </el-button>
        <el-button @click="showSearchDialog = true">
          <el-icon><Search /></el-icon>
          搜索班级圈
        </el-button>
      </div>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" class="circle-tabs">
      <el-tab-pane label="我加入的班级圈" name="joined">
        <div class="circles-container">
          <div v-if="joinedCircles.length === 0" class="empty-state">
            <el-icon :size="64"><School /></el-icon>
            <h3>您还没有加入任何班级圈</h3>
            <p>搜索并加入班级圈，开始您的社交之旅吧！</p>
            <el-button type="primary" @click="showSearchDialog = true">
              搜索班级圈
            </el-button>
          </div>
          
          <div v-else class="circles-grid">
            <div 
              class="circle-card" 
              v-for="circle in joinedCircles" 
              :key="circle.id"
              @click="viewCircleDetail(circle)"
            >
              <div class="circle-header">
                <h3>{{ circle.className }}</h3>
                <el-tag size="small" type="primary">{{ circle.memberCount }}人</el-tag>
              </div>
              <div class="circle-info">
                <p class="circle-desc">{{ circle.description || '暂无描述' }}</p>
                <div class="circle-meta">
                  <span>{{ circle.department }}</span>
                  <span>{{ circle.major }}</span>
                  <span>{{ circle.grade }}</span>
                </div>
                <div class="circle-creator">
                  <el-icon><User /></el-icon>
                  <span>创建者：{{ circle.creatorName }}</span>
                </div>
              </div>
              <div class="circle-actions">
                <el-button size="small" @click.stop="viewMembers(circle)">
                  查看成员
                </el-button>
                <!-- 只有学生可以退出班级圈，教师不能退出 -->
                <el-button 
                  v-if="userInfo.role === 'STUDENT' && String(circle.creatorId) !== userInfo.id" 
                  size="small" 
                  type="danger" 
                  @click.stop="leaveCircle(circle)"
                >
                  退出
                </el-button>
                <el-button 
                  v-if="String(circle.creatorId) === userInfo.id" 
                  size="small" 
                  type="danger" 
                  @click.stop="deleteCircle(circle)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane v-if="userInfo.role === 'TEACHER'" label="我创建的班级圈" name="created">
        <div class="circles-container">
          <div v-if="createdCircles.length === 0" class="empty-state">
            <el-icon :size="64"><School /></el-icon>
            <h3>您还没有创建任何班级圈</h3>
            <p>创建班级圈，邀请学生加入，促进师生交流！</p>
            <el-button type="primary" @click="showCreateDialog = true">
              创建班级圈
            </el-button>
          </div>
          
          <div v-else class="circles-grid">
            <div 
              class="circle-card" 
              v-for="circle in createdCircles" 
              :key="circle.id"
              @click="viewCircleDetail(circle)"
            >
              <div class="circle-header">
                <h3>{{ circle.className }}</h3>
                <el-tag size="small" type="success">创建者</el-tag>
              </div>
              <div class="circle-info">
                <p class="circle-desc">{{ circle.description || '暂无描述' }}</p>
                <div class="circle-meta">
                  <span>{{ circle.department }}</span>
                  <span>{{ circle.major }}</span>
                  <span>{{ circle.grade }}</span>
                </div>
                <div class="circle-stats">
                  <span>{{ circle.memberCount }} 名成员</span>
                </div>
              </div>
              <div class="circle-actions">
                <el-button size="small" @click.stop="viewMembers(circle)">
                  管理成员
                </el-button>
                <el-button size="small" type="danger" @click.stop="deleteCircle(circle)">
                  删除
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建班级圈对话框 -->
    <el-dialog 
      v-model="showCreateDialog" 
      title="创建班级圈" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="createFormRef" 
        :model="createForm" 
        :rules="createRules" 
        label-width="100px"
      >
        <el-form-item label="班级ID" prop="classId">
          <el-input 
            v-model="createForm.classId" 
            placeholder="请输入班级ID，用于学生搜索"
            maxlength="20"
          />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input 
            v-model="createForm.className" 
            placeholder="请输入班级名称"
            maxlength="50"
          />
        </el-form-item>
        <el-form-item label="班级描述" prop="description">
          <el-input 
            v-model="createForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入班级描述"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="所属院系" prop="department">
          <el-input 
            v-model="createForm.department" 
            placeholder="请输入所属院系"
          />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input 
            v-model="createForm.major" 
            placeholder="请输入专业"
          />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input 
            v-model="createForm.grade" 
            placeholder="请输入年级，如：2024级"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="createCircle" :loading="creating">
          创建
        </el-button>
      </template>
    </el-dialog>

    <!-- 搜索班级圈对话框 -->
    <el-dialog 
      v-model="showSearchDialog" 
      title="搜索班级圈" 
      width="400px"
    >
      <el-form @submit.prevent="searchCircle">
        <el-form-item>
          <el-input 
            v-model="searchClassId" 
            placeholder="请输入班级ID"
            @keyup.enter="searchCircle"
          >
            <template #append>
              <el-button @click="searchCircle" :loading="searching">
                <el-icon><Search /></el-icon>
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      
      <div v-if="searchResult" class="search-result">
        <div class="result-card">
          <h4>{{ searchResult.className }}</h4>
          <p>{{ searchResult.description || '暂无描述' }}</p>
          <div class="result-meta">
            <span>{{ searchResult.department }}</span>
            <span>{{ searchResult.major }}</span>
            <span>{{ searchResult.grade }}</span>
            <span>{{ searchResult.memberCount }}人</span>
          </div>
          <div class="result-actions">
            <el-button 
              v-if="!isJoined(searchResult.id)" 
              type="primary" 
              @click="joinCircle(searchResult)"
              :loading="joining"
            >
              加入班级圈
            </el-button>
            <el-tag v-else type="success">已加入</el-tag>
          </div>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="showSearchDialog = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 成员列表对话框 -->
    <el-dialog 
      v-model="showMembersDialog" 
      :title="`${currentCircle?.className} - 成员列表`" 
      width="600px"
    >
      <div v-if="members.length === 0" class="empty-state">
        <p>暂无成员</p>
      </div>
      
      <div v-else class="members-list">
        <div 
          class="member-item" 
          v-for="member in members" 
          :key="member.id"
        >
          <div class="member-info">
            <el-avatar :size="40">
              {{ member.userName.charAt(0) }}
            </el-avatar>
            <div class="member-details">
              <div class="member-name">{{ member.userName }}</div>
              <div class="member-role">
                <el-tag size="small" :type="member.joinType === 'CREATOR' ? 'success' : 'info'">
                  {{ member.joinType === 'CREATOR' ? '创建者' : member.userRole === 'TEACHER' ? '教师' : '学生' }}
                </el-tag>
              </div>
            </div>
          </div>
          <div class="member-actions">
            <div class="member-time">
              {{ formatTime(member.joinTime) }}
            </div>
            <!-- 只有创建者可以删除其他成员，且不能删除自己 -->
            <el-button 
              v-if="userInfo.role === 'TEACHER' && 
                    String(currentCircle?.creatorId) === userInfo.id && 
                    member.joinType !== 'CREATOR'"
              size="small" 
              type="danger" 
              @click="removeMember(member)"
            >
              删除
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  School,
  User,
  ArrowLeft
} from '@element-plus/icons-vue'
import { classCircleApi } from '@/api/social'

export default {
  name: 'ClassCirclePage',
  components: {
    Plus,
    Search,
    School,
    User,
    ArrowLeft
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    
    // 用户信息
    const userInfo = computed(() => store.state.user.userInfo)
    
    // 标签页
    const activeTab = ref('joined')
    
    // 班级圈数据
    const joinedCircles = ref([])
    const createdCircles = ref([])
    
    // 对话框状态
    const showCreateDialog = ref(false)
    const showSearchDialog = ref(false)
    const showMembersDialog = ref(false)
    
    // 创建表单
    const createFormRef = ref()
    const createForm = reactive({
      classId: '',
      className: '',
      description: '',
      department: '',
      major: '',
      grade: ''
    })
    
    const createRules = {
      classId: [
        { required: true, message: '请输入班级ID', trigger: 'blur' },
        { min: 2, max: 20, message: '班级ID长度在2-20个字符', trigger: 'blur' }
      ],
      className: [
        { required: true, message: '请输入班级名称', trigger: 'blur' },
        { min: 2, max: 50, message: '班级名称长度在2-50个字符', trigger: 'blur' }
      ],
      department: [
        { required: true, message: '请输入所属院系', trigger: 'blur' }
      ],
      major: [
        { required: true, message: '请输入专业', trigger: 'blur' }
      ],
      grade: [
        { required: true, message: '请输入年级', trigger: 'blur' }
      ]
    }
    
    // 搜索相关
    const searchClassId = ref('')
    const searchResult = ref(null)
    const searching = ref(false)
    const joining = ref(false)
    const creating = ref(false)
    
    // 成员相关
    const currentCircle = ref(null)
    const members = ref([])
    
    // 加载数据
    const loadData = async () => {
      try {
        // 加载加入的班级圈
        const joinedResponse = await classCircleApi.getMyJoinedCircles()
        if (joinedResponse.code === 200 && joinedResponse.data) {
          joinedCircles.value = joinedResponse.data
        }
        
        // 如果是教师，加载创建的班级圈
        if (userInfo.value.role === 'TEACHER') {
          const createdResponse = await classCircleApi.getMyCreatedCircles()
          if (createdResponse.code === 200 && createdResponse.data) {
            createdCircles.value = createdResponse.data
          }
        }
      } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
      }
    }
    
    // 创建班级圈
    const createCircle = async () => {
      try {
        await createFormRef.value.validate()
        creating.value = true
        
        const response = await classCircleApi.createClassCircle(createForm)
        if (response.code === 200) {
          ElMessage.success('班级圈创建成功')
          showCreateDialog.value = false
          // 重置表单
          Object.keys(createForm).forEach(key => {
            createForm[key] = ''
          })
          // 重新加载数据
          await loadData()
        } else {
          ElMessage.error(response.message || '创建失败')
        }
      } catch (error) {
        console.error('创建班级圈失败:', error)
        ElMessage.error('创建班级圈失败')
      } finally {
        creating.value = false
      }
    }
    
    // 搜索班级圈
    const searchCircle = async () => {
      if (!searchClassId.value.trim()) {
        ElMessage.warning('请输入班级ID')
        return
      }
      
      try {
        searching.value = true
        const response = await classCircleApi.searchClassCircle(searchClassId.value.trim())
        if (response.code === 200 && response.data) {
          searchResult.value = response.data
        } else {
          searchResult.value = null
          ElMessage.warning('未找到该班级圈')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        ElMessage.error('搜索失败')
      } finally {
        searching.value = false
      }
    }
    
    // 加入班级圈
    const joinCircle = async (circle) => {
      try {
        joining.value = true
        const response = await classCircleApi.joinClassCircle(circle.id)
        if (response.code === 200) {
          ElMessage.success('成功加入班级圈')
          showSearchDialog.value = false
          searchResult.value = null
          searchClassId.value = ''
          await loadData()
        } else {
          ElMessage.error(response.message || '加入失败')
        }
      } catch (error) {
        console.error('加入班级圈失败:', error)
        ElMessage.error('加入班级圈失败')
      } finally {
        joining.value = false
      }
    }
    
    // 退出班级圈
    const leaveCircle = async (circle) => {
      try {
        await ElMessageBox.confirm(
          `确定要退出班级圈"${circle.className}"吗？`,
          '确认退出',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await classCircleApi.leaveClassCircle(circle.id)
        if (response.code === 200) {
          ElMessage.success('成功退出班级圈')
          await loadData()
        } else {
          ElMessage.error(response.message || '退出失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('退出班级圈失败:', error)
          ElMessage.error('退出班级圈失败')
        }
      }
    }
    
    // 删除班级圈
    const deleteCircle = async (circle) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除班级圈"${circle.className}"吗？删除后无法恢复！`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await classCircleApi.deleteClassCircle(circle.id)
        if (response.code === 200) {
          ElMessage.success('班级圈删除成功')
          await loadData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除班级圈失败:', error)
          ElMessage.error('删除班级圈失败')
        }
      }
    }
    
    // 查看成员
    const viewMembers = async (circle) => {
      try {
        currentCircle.value = circle
        const response = await classCircleApi.getClassCircleMembers(circle.id)
        if (response.code === 200) {
          members.value = response.data
          showMembersDialog.value = true
        } else {
          ElMessage.error('获取成员列表失败')
        }
      } catch (error) {
        console.error('获取成员列表失败:', error)
        ElMessage.error('获取成员列表失败')
      }
    }

    // 删除成员
    const removeMember = async (member) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除成员"${member.userName}"吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )
        
        const response = await classCircleApi.removeClassCircleMember(currentCircle.value.id, member.id)
        if (response.code === 200) {
          ElMessage.success('成员删除成功')
          // 重新加载成员列表
          await viewMembers(currentCircle.value)
          // 重新加载班级圈数据
          await loadData()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除成员失败:', error)
          ElMessage.error('删除成员失败')
        }
      }
    }
    
    // 查看班级圈详情
    const viewCircleDetail = (circle) => {
      // 这里可以跳转到班级圈详情页面
      ElMessage.info(`查看班级圈：${circle.className}`)
    }
    
    // 检查是否已加入
    const isJoined = (circleId) => {
      return joinedCircles.value.some(circle => circle.id === circleId)
    }
    
    // 格式化时间
    const formatTime = (time) => {
      const date = new Date(time)
      return date.toLocaleString()
    }

    // 返回社交互动页面
    const goBack = () => {
      router.push('/social')
    }
    
    onMounted(() => {
      loadData()
    })
    
    return {
      userInfo,
      activeTab,
      joinedCircles,
      createdCircles,
      showCreateDialog,
      showSearchDialog,
      showMembersDialog,
      createFormRef,
      createForm,
      createRules,
      searchClassId,
      searchResult,
      searching,
      joining,
      creating,
      currentCircle,
      members,
      createCircle,
      searchCircle,
      joinCircle,
      leaveCircle,
      deleteCircle,
      viewMembers,
      removeMember,
      viewCircleDetail,
      isJoined,
      formatTime,
      goBack
    }
  }
}
</script>

<style scoped>
.class-circle-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.back-btn-wrapper {
  text-align: left;
  margin-bottom: 20px;
  margin-left: -8px;
}

.back-btn {
  color: var(--el-color-primary);
  font-size: 15px;
  font-weight: bold;
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 4px 12px 4px 4px;
  border-radius: 6px;
  background: transparent;
  transition: background 0.2s, color 0.2s;
}

.back-btn:hover {
  background: rgba(64, 158, 255, 0.08);
  color: var(--el-color-primary-dark);
  text-decoration: none;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.header-content h1 {
  font-size: 28px;
  color: var(--el-text-color-primary);
  margin-bottom: 8px;
}

.header-content p {
  color: var(--el-text-color-regular);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.circle-tabs {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.circles-container {
  min-height: 400px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--el-text-color-secondary);
}

.empty-state .el-icon {
  margin-bottom: 16px;
  color: var(--el-text-color-placeholder);
}

.empty-state h3 {
  margin-bottom: 8px;
  color: var(--el-text-color-primary);
}

.empty-state p {
  margin-bottom: 20px;
}

.circles-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
}

.circle-card {
  background: white;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 12px;
  padding: 20px;
  cursor: pointer;
  transition: all 0.3s;
}

.circle-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.circle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.circle-header h3 {
  margin: 0;
  color: var(--el-text-color-primary);
  font-size: 18px;
}

.circle-desc {
  color: var(--el-text-color-regular);
  margin-bottom: 12px;
  line-height: 1.5;
}

.circle-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.circle-meta span {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: var(--el-fill-color-light);
  padding: 2px 8px;
  border-radius: 4px;
}

.circle-creator {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 12px;
}

.circle-stats {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  margin-bottom: 12px;
}

.circle-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.search-result {
  margin-top: 20px;
}

.result-card {
  background: var(--el-fill-color-light);
  border-radius: 8px;
  padding: 16px;
}

.result-card h4 {
  margin: 0 0 8px 0;
  color: var(--el-text-color-primary);
}

.result-card p {
  color: var(--el-text-color-regular);
  margin-bottom: 12px;
}

.result-meta {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.result-meta span {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  background: white;
  padding: 2px 8px;
  border-radius: 4px;
}

.result-actions {
  text-align: center;
}

.members-list {
  max-height: 400px;
  overflow-y: auto;
}

.member-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.member-item:last-child {
  border-bottom: none;
}

.member-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.member-details {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.member-name {
  font-weight: 500;
  color: var(--el-text-color-primary);
}

.member-time {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}

.member-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}
</style> 